package com.xiaochi.subject.domain.config;

import com.xiaochi.subject.common.config.ThreadTaskDecorator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * 线程池的config管理
 * @author zqx
 * @since 2024/9/3
 */
@Configuration
public class ThreadPoolConfig {

    @Bean(name = "labelThreadPool")
    public ThreadPoolExecutor getLabelThreadPool(){
        return new ThreadPoolExecutor(20,100,5,
                TimeUnit.SECONDS,new LinkedBlockingQueue<>(40),
                new CustomNameThreadFactory("label"),
                new ThreadPoolExecutor.CallerRunsPolicy());
    }

    // todo 这个线程池相比于 threadPoolExector更加和spring集成，但是不够灵活 需要对spring框架的理解更多，使用时可能好一点
    @Bean(name = "taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(40);
        executor.setKeepAliveSeconds(5);
        executor.setThreadNamePrefix("label-task");
        executor.setTaskDecorator(new ThreadTaskDecorator());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}
